package com.wang.lotterysystem.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wang.lotterysystem.common.errorcode.ServiceErrorCodeConstants;
import com.wang.lotterysystem.common.exception.ServiceException;
import com.wang.lotterysystem.common.utils.RedisUtil;
import com.wang.lotterysystem.common.utils.RegexUtil;
import com.wang.lotterysystem.service.VerificationCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class VerificationCodeServiceImpl implements VerificationCodeService {

    private static final String VERIFICATION_PREFIX = "verification_code_"; //业务前缀,用来区分不同的业务

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public void sendVerificationCode(String phoneNumber) throws JsonProcessingException {
        //校验手机号
        if (!StringUtils.hasText(phoneNumber) || !RegexUtil.checkMobile(phoneNumber)){
            //如果手机号为空或者手机号格式不正确 --> 抛出异常
            throw new ServiceException(ServiceErrorCodeConstants.PHONE_NUMBER_ERROR);
        }

        //4位验证码 (这里mock为"1234")
        String captcha = "1234";

        //将验证码存入redis中
        redisUtil.set(VERIFICATION_PREFIX + phoneNumber,captcha,300L);
    }

    @Override
    public String getVerificationCode(String phoneNumber) {
        //校验手机号
        if (!StringUtils.hasText(phoneNumber) || !RegexUtil.checkMobile(phoneNumber)){
            throw new ServiceException(ServiceErrorCodeConstants.PHONE_NUMBER_ERROR);
        }
        return redisUtil.get(VERIFICATION_PREFIX + phoneNumber);
    }

}
